package com.emm.yixun.website.listeners;

import java.io.Serializable;
import java.util.Date;
import java.util.List;

import org.activiti.engine.delegate.DelegateExecution;
import org.activiti.engine.delegate.ExecutionListener;

import com.emm.yixun.common.enums.ResponseEnums;
import com.emm.yixun.common.model.ActcommitLog;
import com.emm.yixun.common.model.BusinessAbnorma;
import com.emm.yixun.common.model.Subscribe;
import com.emm.yixun.common.model.dto.ActcommitLogDto;
import com.emm.yixun.common.model.dto.BusinessAbnormaDto;
import com.emm.yixun.common.model.dto.NoticeEntity;
import com.emm.yixun.common.model.dto.SubscribeDto;
import com.emm.yixun.common.model.enums.AuditStatusEnum;
import com.emm.yixun.common.response.Response;
import com.emm.yixun.common.response.ResponseList;
import com.emm.yixun.customer.service.SubscribeServiceFacade;
import com.emm.yixun.marketing.service.BusinessAbnormaServiceFacade;
import com.emm.yixun.system.service.notice.subscribe.SubscribeDelaySignedNoticeFacade;
import com.emm.yixun.website.common.utils.SpringWebContextUtil;
import com.emm.yixun.website.service.ActivitiProcessServiceImpl;
import com.emm.yixun.website.service.system.log.ActCommitLogService;

public class SubscribeDelaySingedListeners implements Serializable, ExecutionListener{
	private static final long serialVersionUID = -5623735222280919582L;

	@Override
	public void notify(DelegateExecution execution) throws Exception {
		SubscribeServiceFacade subscribeServiceFacade=getSubscribeServiceFacade();
		BusinessAbnormaServiceFacade businessAbnormaServiceFacade=getBusinessAbnormaServiceFacade();
		String businessAbnormaId=execution.getProcessBusinessKey();
		String processInstanceId=execution.getProcessInstanceId();
		Response<BusinessAbnorma> businessAbnormaResponse=businessAbnormaServiceFacade.findById(Long.valueOf(businessAbnormaId));
		if(!businessAbnormaResponse.isSuccess()){
			throw new Exception("认购延期签约记录不存在");
		}
		BusinessAbnorma businessAbnorma=businessAbnormaResponse.getEntity();
		if(null==businessAbnorma){
			throw new Exception("认购延期签约记录不存在");
		}
		
		Response<Subscribe> payDepositResponse=subscribeServiceFacade.findById(businessAbnorma.getBusinessId());
		if(!payDepositResponse.isSuccess()){
			throw new Exception("认购记录不存在");
		}
		Subscribe subscribe=payDepositResponse.getEntity();
		if(null==subscribe){
			throw new Exception("认购记录不存在");
		}
		
		if(getActivitiProcessServiceImpl().isCheckPass(processInstanceId)){
			
			boolean flag = checkAuditCommit(businessAbnorma);
			if(!flag) {
				throw new Exception(ResponseEnums.RESPONSEENUMS_999999.getName());
			}
			
			//认筹记录标示为解除认筹
			SubscribeDto updatePddDto=new SubscribeDto();
			updatePddDto.setId(subscribe.getId());
			//业务状态修改为延期签约
			//延期签约成功，无需修改业务状态为延期签约(ym)
			//updatePddDto.setBusinessStatus("6");
			//延期签约时间默认为当天
			updatePddDto.setConversionSignDate(businessAbnorma.getDelaydate());
			//更改延期签约时间
			Response<Integer> responseUudate=subscribeServiceFacade.updateByPrimaryKey(updatePddDto,true);
			if(!responseUudate.isSuccess()){
				throw new Exception("认购记录标示为解除认筹出错");
			}
			
			//更新审核状态
			BusinessAbnormaDto updateDto=new BusinessAbnormaDto();
			updateDto.setId(businessAbnorma.getId());
			updateDto.setAuditStatus(AuditStatusEnum.SUCCESS.getNo());
			updateDto.setCheckDate(new Date());
			Response<Integer> responseBusinessAbnormaDto=businessAbnormaServiceFacade.updateByPrimaryKey(updateDto, true);
			if(!responseBusinessAbnormaDto.isSuccess()){
				throw new Exception("更新延期签约审核状态出错");
			}
			
			/**
			 * （延期签约流程审核通过）推送消息到app
			 * @author ny
			 * @param param noticeType 提醒类型, noticeBusinessId 业务主键Id，timeType延期天数类型
			 */
			Long delayDays = com.emm.yixun.common.utils.DateUtils.getDaysSub(businessAbnorma.getConversionSignDate(), businessAbnorma.getDelaydate());
			String timeType = "";
			if (0 < delayDays && delayDays <= 15) {
				timeType = "1";
			}else if (15 < delayDays && delayDays <= 30) {
				timeType = "2";
			}else if (delayDays > 30) {
				timeType = "3";
			}
			NoticeEntity noticeEntity = new NoticeEntity();
			noticeEntity.setNoticeBusinessId(subscribe.getId());
			noticeEntity.setNoticeType("12");
			noticeEntity.setTimeType(timeType);
			noticeEntity.setProcessInstanceId(processInstanceId);
			getSubscribeDelaySignedNoticeFacade().createSubscribeDelaySignedNotice(noticeEntity);
		}else{
			
			boolean flag = checkAuditCommit(businessAbnorma);
			if(!flag) {
				throw new Exception(ResponseEnums.RESPONSEENUMS_999999.getName());
			}
			
			//更新审核状态
			BusinessAbnormaDto updateDto=new BusinessAbnormaDto();
			updateDto.setId(businessAbnorma.getId());
			updateDto.setAuditStatus(AuditStatusEnum.REJECT.getNo());
			updateDto.setCheckDate(new Date());
			Response<Integer> responseBusinessAbnormaDto=businessAbnormaServiceFacade.updateByPrimaryKey(updateDto, true);
			if(!responseBusinessAbnormaDto.isSuccess()){
				throw new Exception("更新延期签约审核状态出错");
			}
			
			/**
			 * （延期签约流程审核不通过）推送消息到app
			 * @author ny
			 * @param param noticeType 提醒类型, noticeBusinessId 业务主键Id
			 * @return 延期签约审核结果【${auditStatus}】房号：${roomName}；客户：${customer};
			 */
			Long delayDays = com.emm.yixun.common.utils.DateUtils.getDaysSub(businessAbnorma.getConversionSignDate(), businessAbnorma.getDelaydate());
			String timeType = "";
			if (0 < delayDays && delayDays <= 15) {
				timeType = "1";
			}else if (15 < delayDays && delayDays <= 30) {
				timeType = "2";
			}else if (delayDays > 30) {
				timeType = "3";
			}
			NoticeEntity noticeEntity = new NoticeEntity();
			noticeEntity.setNoticeBusinessId(subscribe.getId());
			noticeEntity.setNoticeType("12");
			noticeEntity.setTimeType(timeType);
			noticeEntity.setProcessInstanceId(processInstanceId);
			getSubscribeDelaySignedNoticeFacade().createSubscribeDelaySignedNotice(noticeEntity);
		}
	}
	
	/**
	 * 前置判断,审核记录是否已经提交,防止重复提交
	 * 产生原因: 提交审核,后台处理中时,刷新页面再次提交审核,会重复
	 * true: 可继续执行
	 * false: 不可执行
	 */
	public boolean checkAuditCommit(BusinessAbnorma entity) {
		// 业务数据为null时,默认通过.为了不改变老业务,不影响流程正常行走
		if (null == entity) {
			return true;
		}
		return getActcommitLogService().checkActCommit(entity.getAuditStatus(), entity.getMerchantId(), entity.getId(),
				entity.getProcInstId(), "认购延期", "PC");
	}
	
	private ActCommitLogService getActcommitLogService(){
		return (ActCommitLogService)SpringWebContextUtil.getApplicationContext().getBean("actCommitLogService");
	}
	
	private SubscribeDelaySignedNoticeFacade getSubscribeDelaySignedNoticeFacade(){
		return (SubscribeDelaySignedNoticeFacade)SpringWebContextUtil.getApplicationContext().getBean("subscribeDelaySignedNoticeFacade");
	}
	
	private BusinessAbnormaServiceFacade getBusinessAbnormaServiceFacade(){
		return (BusinessAbnormaServiceFacade)SpringWebContextUtil.getApplicationContext().getBean("businessAbnormaServiceFacade");
	}
	
	private ActivitiProcessServiceImpl getActivitiProcessServiceImpl(){
		return (ActivitiProcessServiceImpl)SpringWebContextUtil.getApplicationContext().getBean("activitiProcessServiceImpl");
	}
	
	private SubscribeServiceFacade getSubscribeServiceFacade(){
		return (SubscribeServiceFacade)SpringWebContextUtil.getApplicationContext().getBean("subscribeServiceFacade");
	}

}
